package com.xmall.validate;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 金额格式验证
 */
public class MoneyValidator implements ConstraintValidator<Money, BigDecimal> {

    private static final Pattern PATTERN = Pattern.compile("^[0-9]+(\\.[0-9]{0,2})?$");

    @Override
    public boolean isValid(BigDecimal value, ConstraintValidatorContext context) {
        if (value != null) {
            Matcher matcher = PATTERN.matcher(value.toString());
            return matcher.find();
        }
        return true;
    }
}
